<?php

	class Plugins
	{
		private $plugin_filenames = Array(
			"%name%Plugin", "Base%name%Plugin"
		);
		
		private $dir_plugins = "../plugins/";
		
		function __construct( &$dash )
		{
			$this->master =& $dash;
			$this->config =& $dash->config;
			
			if ( $this->config->directories )
			{
				$this->dir_plugins = $this->config->directories->plugins;
				$this->dir_queries = $this->config->directories->queries;
			}
		}
		
		public function executePlugin( $namespace, $method )
		{
			if ( ! $class_instance = $this->loadPlugin( $namespace ) )
				return false;
			
			// find the name of the class from instance created
			$class_name = get_class( $class_instance );
			
			// get a reflection instance of the controller
			$class_info = new ReflectionClass( $class_name );

			// Check that the function exists
			if ( ! $class_info->hasMethod( $method ) )
				return false;
			
			$method_ref = new ReflectionMethod( $namespace, $method );			
			
			// Check the parameters 
			$method_params = $method_ref->getParameters();
			
			// validate the call and return an array of callable parameters, in proper order
			if ( $callable_params = $this->validateParams( $params, $method_params ) )
				// make the call and return the result
				return $class_info->invokeArgs( $class_instance, $callable_params );
				
			return false;
		}
		
		public function getPlugin( $namespace )
		{
			$namespace = strtolower( $namespace );
			
			if ( ! isset( $this->instances[ $namespace ] ) )
				$this->instances[ $namespace ] = $this->loadPlugin( $namespace );
			
			return $this->instances[ $namespace ];
		}
		
		public function loadPlugin( $namespace )
		{
			foreach( $this->plugin_filenames AS $format )
			{
				$class_name = str_replace( "%name%", $namespace, $format );
				
				if ( ! class_exists( $class_name ) )
				{
					// if the class doesn't already exist try to find the file
					if ( ! file_exists( $this->dir_plugins . $class_name . ".php" ) )
						continue; // can't find the plugin! move to next format
					else
						require_once( $this->dir_plugins . $class_name . ".php" );
				}
				
				// found and loaded the controller
				return new $class_name( $this );
			}
			
			return false;
		}
	}

?>
